#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2020-04-24 04:29:08
# Project: test1
import re
from pyspider.libs.base_handler import *


HTML_ORG_PATTERN = re.compile('https?://\S+\.(?:jpg|png|jpeg)', re.I)


class Handler(BaseHandler):
    crawl_config = {
    }

    @every(minutes=24 * 60)
    def on_start(self):
        headers = {}
        headers["Content-Type"] = "application/x-www-form-urlencoded"
        headers["User-Agent"] = "PostmanRuntime/7.24.1"
        headers["Accept"] = "*/*"
        headers["Accept-Encoding"] = "gzip, deflate, br"
        headers["Connection"] = "keep-alive"
        data = {}
        data["goodId"] = "5c228d114e1644408e81b3e1baebd0eb"
        self.crawl('https://wxmini.baixingliangfan.cn/baixing/wxmini/getGoodDetailById', data=data,
                   callback=self.index_page, headers=headers, method="POST")

    @config(age=10 * 24 * 60 * 60)
    def index_page(self, response):
        goodsDetail = response.json['data']['goodInfo']['goodsDetail']
        print(goodsDetail)
        for img_url in HTML_ORG_PATTERN.findall(goodsDetail):
            self.crawl(img_url, callback=self.detail_page)

    @config(priority=2)
    def detail_page(self, response):
        return {
            "url": response.url,
            "title": response.doc('title').text(),
        }
